<template>
    <div class="app-container tz-app">
        <div class="zt-select flex-s">
            <div class="flex-left flex-item">
                <div class="query-text">本机:</div>
                <el-select v-model="queryParams.antennaName" filterable placeholder="台站" class="zt-input-min rihgt-m5">
                    <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.label">
                    </el-option>
                </el-select>
                <div class="query-text">对方:</div>
                <el-select v-model="queryParams.antennaName" filterable placeholder="台站" class="zt-input-min rihgt-m5">
                    <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.label">
                    </el-option>
                </el-select>


                <el-date-picker v-model="queryParams.time" type="datetimerange" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>

                <!-- <button class="bt-blue " @click="handleQuery">筛选</button> -->
            </div>
            <!-- <button class="bt-yellow " @click="handleAdd">新增</button> -->
            <button class="bt-blue " @click="handleQuery">筛选</button>

        </div>

        <div class="tz-table-box" style="height:calc(100vh - 250px);">
            <el-table v-loading="loading" :data="roomList" @selection-change="handleSelectionChange"
                height="calc(100vh - 250px)" class="zt-table">
                <el-table-column label="机房编号" align="center" prop="machineRoomId" />
                <el-table-column label="机房名称" align="center" prop="machineRoomName" />
                <el-table-column label="机房类型" align="center" prop="machineRoomType" />
                <el-table-column label="所属台站" align="center" prop="locatedAddress" />
                <el-table-column label="状态" align="center" prop="status" />
                <el-table-column label="备注" align="center" prop="remark" />
                <el-table-column label="节点ID" align="center" prop="regionalNodeId" />
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <img src="@/assets/images/amend.png" class="icon-img" @click="handleUpdate(scope.row)" />
                        <img src="@/assets/images/delete-bin2.png" class="icon-img" @click="handleDelete(scope.row)" />
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />


    </div>
</template>

<script>
import { listRoom, getRoom, delRoom, addRoom, updateRoom } from "@/api/business/room";

import { getAntennaListAll } from "@/api/business/antenna";//天线
import { getSensorListAll } from "@/api/business/sensor";//传感器
import { getCameraListAll } from "@/api/business/camera";//摄像头
import { getRadioStationList } from "@/api/business/station";//电台


import RightDialog from "@/components/TZ/RightDialog"
import TSelect from "@/components/TZ/TSelect"

export default {
    components: { RightDialog, TSelect },
    dicts: ['located_address'],
    name: "Room",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 机房表格数据
            roomList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                time: null,
                machineRoomName: null,
                machineRoomType: null,
                locatedAddress: null,
                status: null,
                regionalNodeId: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {

            },
            options: [{
                value: '1',
                label: '1'
            }, {
                value: '天线',
                label: '天线'
            }, {
                value: '2',
                label: '2'
            }, {
                value: '3',
                label: '3'
            }, {
                value: '天下七七',
                label: '天下七七'
            }],
            typeListAll: false,//type:true=新增,false=修改 
            antennaListAll: [//天线集合
                { label: '已使用', options: [] },
                { label: '未使用', options: [] },
            ],
            pltSensorListAll: [//传感器集合
                { label: '已使用', options: [] },
                { label: '未使用', options: [] },
            ],
            pltCameraListAll: [//摄像头集合
                { label: '已使用', options: [] },
                { label: '未使用', options: [] },
            ],
            pltRadioStationList: [//电台集合
                { label: '已使用', options: [] },
                { label: '未使用', options: [] },
            ],
            beforeForm: {
                pltSensorList: [],//传感器集合
                pltCameraList: [],//摄像头集合
                stationList: [],//电台集合
            },

        };
    },
    created() {
        this.getList();
    },
    methods: {
        async getListAll(index) {//查询数据集合 

            this.resetListAll();
            const data = {
                locatedAddress: index,
                isUsed: 0,
            }
            await getSensorListAll(data).then(response => {
                this.pltSensorListAll[1].options = response.rows;
            });
            await getCameraListAll(data).then(response => {
                this.pltCameraListAll[1].options = response.rows;
            });
            await getRadioStationList(data).then(response => {
                this.pltRadioStationList[1].options = response.rows;
            });
        },
        get() {

            console.log(this.form.sensorIds);
            this.form.pltSensorList = this.form.sensorIds.map(item => ({ sensorId: item }));
        },
        changeLocatedAddress(index) {
            this.form.sensorIds = [];
            this.form.cameraIds = [];
            this.form.radioStationIds = [];
            this.getListAll(index);
            console.log(this.form);
        },

        /** 查询机房列表 */
        getList() {
            this.loading = true;
            listRoom(this.queryParams).then(response => {
                this.roomList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        resetListAll() {//重置查询集合
            this.antennaListAll = [//天线集合
                { label: '已使用', options: [] },
                { label: '未使用', options: [] },
            ]
            this.pltSensorListAll = [//传感器集合
                { label: '已使用', options: [] },
                { label: '未使用', options: [] },
            ]
            this.pltCameraListAll = [//摄像头集合
                { label: '已使用', options: [] },
                { label: '未使用', options: [] },
            ]
            this.pltRadioStationList = [//电台集合
                { label: '已使用', options: [] },
                { label: '未使用', options: [] },
            ]
        },
        // 表单重置
        reset() {
            this.form = {
                machineRoomId: null,
                machineRoomName: null,
                machineRoomType: null,
                locatedAddress: null,
                status: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null,
                regionalNodeId: null,
                pltSensorList: null,
                pltRadioStationList: null,
                pltCameraList: null,
                sensorIds: null,
                cameraIds: null,
                radioStationIds: null,
            };
            this.resetForm("form");

        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.machineRoomId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加机房";
            this.typeListAll = true;
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const machineRoomId = row.machineRoomId || this.ids
            getRoom(machineRoomId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改机房";
                this.typeListAll = false;
                this.getListAll(this.form.locatedAddress);
                this.transitionList();
            });
        },
        setListAll() {//将要提交的数据转为后端需要的格式

            //传感器
            let data = []
            if (this.pltSensorListAll[0].options.length >= 1) data = this.pltSensorListAll[0].options;//该数据存在未使用添加进提交数据
            this.form.pltSensorList = this.form.sensorIds.map(item => ({ sensorId: item, isUsed: 1 }));
            this.form.pltSensorList = this.form.pltSensorList.concat(data);
            //摄像头
            data = []
            if (this.pltCameraListAll[0].options.length >= 1) data = this.pltCameraListAll[0].options;
            this.form.pltCameraList = this.form.cameraIds.map(item => ({ cameraId: item, isUsed: 1 }));
            this.form.pltCameraList = this.form.pltCameraList.concat(data);
            //电台
            data = []
            if (this.pltRadioStationList[0].options.length >= 1) data = this.pltRadioStationList[0].options;
            this.form.pltRadioStationList = this.form.radioStationIds.map(item => ({ radioStationId: item, isUsed: 1 }));
            this.form.pltRadioStationList = this.form.pltRadioStationList.concat(data);
            this.reduceData();

        },
        reduceData() {
            // 使用reduce来过滤数据
            this.form.pltRadioStationList = this.form.pltRadioStationList.reduce((filtered, item) => {
                // 检查是否已经有相同 radioStationId 的记录
                let existingItem = filtered.find(i => i.radioStationId === item.radioStationId);
                // 如果存在，且 isUsed 为0，则保留已有的记录
                if (existingItem) {
                    if (item.isUsed === 1) {
                        existingItem.isUsed = 1;
                    }
                } else {
                    // 如果不存在，直接添加到 filtered 数组
                    filtered.push(item);
                }
                return filtered;
            }, []);
            this.form.pltCameraList = this.form.pltCameraList.reduce((filtered, item) => {
                let existingItem = filtered.find(i => i.cameraId === item.cameraId);
                if (existingItem) {
                    if (item.isUsed === 1) {
                        existingItem.isUsed = 1;
                    }
                } else {
                    filtered.push(item);
                }
                return filtered;
            }, []);
            this.form.pltSensorList = this.form.pltSensorList.reduce((filtered, item) => {
                let existingItem = filtered.find(i => i.sensorId === item.sensorId);
                if (existingItem) {
                    if (item.isUsed === 1) {
                        existingItem.isUsed = 1;
                    }
                } else {
                    filtered.push(item);
                }
                return filtered;
            }, []);
        },
        transitionList() {//将用户拥有的数据转为ids用于多选器展示,并且储存原本的拥有的用户数据。后续提交直接合并提交这个数据,reduceData()提交过程会过滤。同时需要将已拥有的数据放入展示页面
            //因为原本的ids结构没有了需要用set赋值
            //传感器
            this.$set(this.form, 'sensorIds', this.form.pltSensorList ? this.form.pltSensorList.map(item => item.sensorId) : [])
            this.pltSensorListAll[0].options = this.form.pltSensorList.map(item => ({ sensorId: item.sensorId, isUsed: 0, sensorName: item.sensorName, isUsed: 0 }))
            //摄像头
            this.$set(this.form, 'cameraIds', this.form.pltCameraList ? this.form.pltCameraList.map(item => item.cameraId) : [])
            this.pltCameraListAll[0].options = this.form.pltCameraList.map(item => ({ cameraId: item.cameraId, isUsed: 0, cameraName: item.cameraName, isUsed: 0 }))
            console.log(this.form.pltSensorList);
            //电台
            this.$set(this.form, 'radioStationIds', this.form.pltRadioStationList ? this.form.pltRadioStationList.map(item => item.radioStationId) : [])
            this.pltRadioStationList[0].options = this.form.pltRadioStationList.map(item => ({ radioStationId: item.radioStationId, isUsed: 0, radioStationName: item.radioStationName, isUsed: 0 }))
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.setListAll();
                    if (this.form.machineRoomId != null) {
                        updateRoom(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addRoom(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const machineRoomIds = row.machineRoomId || this.ids;
            this.$modal.confirm('是否确认删除机房编号为"' + machineRoomIds + '"的数据项？').then(function () {
                return delRoom(machineRoomIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('system/room/export', {
                ...this.queryParams
            }, `room_${new Date().getTime()}.xlsx`)
        }
    }
};
</script>